<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2014/10/9
 * Time: 11:28
 * 网点表（客户表）
 */
class NetWork extends CActiveRecord
{
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    public function tableName()
    {
        return 'network';
    }
    //级别，有些没有支行，直接到网点
    const NETWORK_LEVEL_ONE = 1;  //网点等级：总行
    const NETWORK_LEVEL_TWO = 2;  //网点等级：分行
    const NETWORK_LEVEL_THREE = 3;  //网点等级：支行
    const NETWORK_LEVEL_FOUR = 4;  //网点等级：网点
	const NETWORK_LEVEL_FIVE = 5;  //网点等级：竞争网点，特殊处理：只是起到标识作用，暂时无实际意义，如果后期需要使用，直接使用即可，默认所有的竞争银行的上级网点为当前问卷的总行
	
    /*
     * 获取项目所有状态
     */
    public static function networkLevel(){
            return array(
                    self::NETWORK_LEVEL_ONE => array(
                            'key' => 'NETWORK_LEVEL_ONE',
                            'desc' => '总行'
                    ),
                    self::NETWORK_LEVEL_TWO => array(
                            'key' => 'NETWORK_LEVEL_TWO',
                            'desc' => '分行'
                    ),
                    self::NETWORK_LEVEL_THREE => array(
                            'key' => 'NETWORK_LEVEL_THREE',
                            'desc' => '支行'
                    ),
                    self::NETWORK_LEVEL_FOUR => array(
                            'key' => 'NETWORK_LEVEL_FOUR',
                            'desc' => '网点'
                    ),
                    //self::NETWORK_LEVEL_FIVE => array(
                    //        'key' => 'NETWORK_LEVEL_FIVE',
                    //        'desc' => '竞争网点'
                    //),
            );
    }
    /**
     * 根据网点编号得到网点信息
     * 不同银行网点编号可能有重复
     */
    public function getByNetworkNum($network_num,$bank_id){
        if ($info = $this->find('network_num=:network_num and bank_id=:bank_id', array(':network_num' => $network_num,':bank_id' => $bank_id))){
            return $info->attributes;
        }
        return $info;
    }
    /**
     * 得到一个银行某个等级的网点
     * @param $up_network_id
     * @param $level 级别
     */
    public function getLevel($up_network_id, $level=0){
        $criteria = new CDbCriteria();
        $criteria->addColumnCondition(array('up_network_id' => $up_network_id));
        if ($level) {
            $criteria->addColumnCondition(array('level' => $level));
        }
        $data = $this->findAll($criteria);
        if ($data) {
            $result = array();
            foreach ($data as $val) {
                $result[$val['network_id']] = $val['network_name'];
            }
            return $result;
        }
        return $data;
    }
    /**
     * 根据网点id得到此网点的下级的所有网点
     * @param $network_id 网点ID
     * @param $level 网点级别
     */
    public function getAllNext($network_id,$level){
        $result = array();
        if ($level == 2) {//二级,找到三四级
            $grade_3  = $this->findAll('up_network_id='.$network_id.' and auth_grade=3');
            
            if ($grade_3) {//如果有三级
                foreach ($grade_3 as $key => $val) {
                    $result[] = $val;
                    $grade_4 = $this->findAll('up_network_id='.$val['network_id'].' and auth_grade=4');
                    if ($grade_4) {
                        foreach ($grade_4 as $k => $v) {
                            $result[] = $v;
                        }
                    }
                }
            } else {//二级下直接四级
                $grade_4 = $this->findAll('up_network_id='.$network_id.' and auth_grade=4');
                if ($grade_4) {
                    foreach ($grade_4 as $k => $v) {
                        $result[] = $v;
                    }
                }
            }
        }
        if ($level == 3) {//三级，找到四级网点即可
            $grade_4 = $this->findAll('up_network_id='.$network_id.' and auth_grade=4');
            if ($grade_4) {
                foreach ($grade_4 as $k => $v) {
                    $result[] = $v;
                }
            }
        }
        return $result;
    }
	
	/**
	 * 根据当前的网点级别获取上级网点级别
	 * @param type $level
	 * @return boolean|int
	 */
	public static function getUpLevel($level){
		if (!$level) {
			return false;
		}
		$upLevel = null;
		switch ($level){
			case self::NETWORK_LEVEL_FIVE:
				$upLevel = array(self::NETWORK_LEVEL_FOUR, self::NETWORK_LEVEL_THREE, self::NETWORK_LEVEL_TWO, self::NETWORK_LEVEL_ONE);
				break;
			case self::NETWORK_LEVEL_FOUR:
				$upLevel = array(self::NETWORK_LEVEL_THREE, self::NETWORK_LEVEL_TWO, self::NETWORK_LEVEL_ONE);
				break;
			case self::NETWORK_LEVEL_THREE:
				$upLevel = array(self::NETWORK_LEVEL_TWO, self::NETWORK_LEVEL_ONE);
				break;
			case self::NETWORK_LEVEL_TWO:
				$upLevel = array(self::NETWORK_LEVEL_ONE);
				break;
			case self::NETWORK_LEVEL_ONE:
				$upLevel = array(0);
				break;
			default :
				break;
		}
		if (is_null($upLevel)) {
			return false;
		}
		return $upLevel;
	}
	
	/**
	 * 格式化出列表或者导出时所需要的列表信息（上级银行，网点级别，上级网点……）
	 * @param type $networkDatas
	 * @return type
	 */
	public function listNetwork($networkDatas){
		$networkDatas = is_array($networkDatas) ? $networkDatas : array($networkDatas);
		
		foreach ($networkDatas as $key => $data) {
			if($data['bank_id']){
				$networkbankModel = NetworkBank::model();
				$networkBank = $networkbankModel->find('bank_id=:bank_id', array(':bank_id' => $data['bank_id']));
				$networkDatas[$key]['bank_name'] = $networkBank->bank_name;
			}
			
			if ($data['level'] || $data['auth_grade']) {
				$levels = self::networkLevel();
				$networkDatas[$key]['level_name'] = $levels[$data['level']]['desc'];
				$networkDatas[$key]['auth_grade_name'] = $levels[$data['auth_grade']]['desc'];
			}
			if ($data['up_network_id']) {
				$network = $this->find('network_id=:up_network_id', array(':up_network_id' => $data['up_network_id']));
				$networkDatas[$key]['up_network_num'] = $network->network_num;
				$networkDatas[$key]['up_network_name'] = $network->network_name;
			}
			if ($data['user_id']) {
				$manageUserModel = ManageUser::model();
				$user = $manageUserModel->find('user_id=:user_id', array(':user_id' => $data['user_id']));
				$networkDatas[$key]['user_name'] = $user->username;
			}
		}
		
		return $networkDatas;
	}


	/**
	 * 单独添加网点，添加时判定是否验证上级编号，默认验证
	 *	注意：如果需要验证上级编号，传入的数组中应确定要存在“up_network_num”，否则提示，添加失败
	 * @param array $item		单独添加网点的数据
	 * @param type $isCheckUp	网点导入时为true，表示强制验证“上级网点编号”，别处使用时，则为false，即不存在up_network_num，将其更改为up_network_id, 直接插入数据库
	 * @return string
	 */
	public function addSingleNetwork(array $item, $isCheckUp = true){
		$return = array(
			'ok' => fasle,
			'msg' => ''
		);
		if(empty($item)){
			$return['msg'] = '插入数据为空';
			return $return;
		}
		
		# 不存在跳过
		if(!isset($item['network_name']) || !$item['network_name']){
			$return['msg'] = '网点名称不存在';
			return $return;
		}
		
		if($isCheckUp){
			if(!isset($item['up_network_num'])){
				$return['msg'] = '导入文件列名不存在“上级编号”';
				return $return;
			}
		}
		
		# 是否检查上级ID
		$networkModel = new NetWork();
		$allLevels = self::networkLevel();
//		unset($allLevels[self::NETWORK_LEVEL_ONE]); //如果不检查总行，直接去掉这一行
		if( in_array( $item['level'], array_keys($allLevels))){  
			
			//不检查“总行”的上级网点，总行没有上级网点
			$upLevel = self::getUpLevel($item['level']);
			if (!$upLevel) {
				$return['msg'] = '当前检查的网点级别不存在对应的上级网点级别，请检查';
				return $return;
			}
			
			// 如果excel中上级编号存在，则表示不是总行，开始验证上级网点
			if ($item['up_network_num']) {
				$criteria = new CDbCriteria();
				$criteria->addInCondition('`level`', $upLevel);
				if ($isCheckUp) {
					$criteria->addCondition('network_num="'.$item['up_network_num'].'"');
				}else{
					$criteria->addCondition('network_id='.$item['up_network_id']);
				}
                                $criteria->addColumnCondition(array('bank_id' => $item['bank_id']));
				$networkData = $networkModel->find($criteria);
				if (!$networkData) {
					$return['msg'] = '上级网点不存在，请检查';
					return $return;
				}
				if ($isCheckUp) {
					unset($item['up_network_num']);
					$item['up_network_id'] = $networkData->network_id;
				}
			}
			
		}else{
			$tmpAllLevels = $allLevels;
			unset($tmpAllLevels[self::NETWORK_LEVEL_FIVE]);
			$tmps = array();
			foreach ($tmpAllLevels as $oneL) {
				$tmps[] = $oneL['desc'];
			}
			$return['msg'] = '当前检查的网点级别不存在于规定的网点级别 ('.join(',', $tmps).') 中，请检查';
			return $return;
		}
		
		# 检查通过，插入数据库
		$item['user_id'] = Yii::app()->session['user_id'];
		$networkData = $networkModel->find('network_num=:network_num and bank_id=:bank_id', array(':network_num' => $item['network_num'], ':bank_id' => $item['bank_id']));
		if ($networkData) {
			$item['update_time'] = time();
			NetWork::model()->updateByPk($networkData->network_id, $item);
			$networkId = $networkData->network_id; #存在网点，修改后返回网点id
		} else {

			#不存在网点，插入
			if(isset($item['up_network_num'])){
				unset($item['up_network_num']);
			}
			foreach ($item as $field => $value) {
				$networkModel->$field = $value;
			}
			$networkModel->create_time = time();
			$saveSta = $networkModel->save();
			if(!$saveSta){
				$return['msg'] = '添加新网点失败';
				return $return;
			}
			$networkId = $networkModel->attributes['network_id'];
		}

		$return = array(
			'ok' => true,
			'msg' => $networkId
		);
		
		return $return;
	}




	/**
	 * 网点上传--插入网点，系统中不存在的网点添加，已经存在更新后返回网点ID，同时验证信息中是否携带有上级网点编号，有：则验证上级网点的准确性，无：不验证
	 * @param array $inData
	 * @return boolean
	 */
	public function addImportNetwork(array $networks){
		if (empty($networks)) {
			return false;
		}
		
		$return = array(
			'ok' => true,
			'msg' => array()
		);
		
		// 先归类网点
		$newNetwork = array();
		foreach ($networks as $key => $item) {
			$newNetwork[$item['level']][$key] = $item;
		}
		
		// 分别依次添加（总行-分行-支行-网点）
		$levelKeys = array_keys($newNetwork);
		sort($levelKeys);
		foreach ($levelKeys as $value) {
			foreach ($newNetwork[$value] as $key => $item) {
				$res = $this->addSingleNetwork($item);
				$return['ok'] &= $res['ok'];
				$return['msg'][$key] = $res['msg'];
			}
		}
		return $return;
	}
	
}